package com.ruoyi.system.service.impl;

import com.ruoyi.system.config.RabbitMQConfig;
import com.ruoyi.system.domain.message.ScheduleNotificationMessage;
import com.ruoyi.system.service.ScheduleNotificationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 排班通知服务实现类
 *
 * @author ruoyi
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ScheduleNotificationServiceImpl implements ScheduleNotificationService {

    private final RabbitTemplate rabbitTemplate;

    @Override
    public void sendScheduleNotification(ScheduleNotificationMessage message) {
        try {
            // 手动转换为JSON字符串
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            String jsonMessage = objectMapper.writeValueAsString(message);

            rabbitTemplate.convertAndSend(
                RabbitMQConfig.SCHEDULE_NOTIFICATION_EXCHANGE,
                RabbitMQConfig.SCHEDULE_NOTIFICATION_ROUTING_KEY,
                jsonMessage
            );
            log.info("发送排班通知成功: 警员={}, 类型={}, 内容={}",
                    message.getOfficerName(), message.getMessageType(), message.getContent());
        } catch (Exception e) {
            log.error("发送排班通知失败: {}", message, e);
        }
    }

    @Override
    public void sendScheduleCreateNotification(Long officerId, String officerName,
                                             String shiftName, Date scheduleDate) {
        ScheduleNotificationMessage message = new ScheduleNotificationMessage(
            officerId, officerName, "CREATE",
            "新排班通知",
            String.format("您有新的排班安排：%s，时间：%tF", shiftName, scheduleDate),
            scheduleDate, shiftName
        );
        sendScheduleNotification(message);
    }

    @Override
    public void sendScheduleUpdateNotification(Long officerId, String officerName,
                                             String shiftName, Date scheduleDate) {
        ScheduleNotificationMessage message = new ScheduleNotificationMessage(
            officerId, officerName, "UPDATE",
            "排班变更通知",
            String.format("您的排班已更新：%s，时间：%tF", shiftName, scheduleDate),
            scheduleDate, shiftName
        );
        sendScheduleNotification(message);
    }

    @Override
    public void sendScheduleDeleteNotification(Long officerId, String officerName,
                                             String shiftName, Date scheduleDate) {
        ScheduleNotificationMessage message = new ScheduleNotificationMessage(
            officerId, officerName, "DELETE",
            "排班取消通知",
            String.format("您的排班已取消：%s，时间：%tF", shiftName, scheduleDate),
            scheduleDate, shiftName
        );
        sendScheduleNotification(message);
    }
}
